// pages/ucenter/withdrawal/withdrawal.js

import * as API_Account from '../../../api/account.js';
const app = getApp();
const _imgUrlHost = 'https://localhost/images/';
let _this;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    accountType: [
      {
        typeIndex: 2,
        typeImg: `${_imgUrlHost}wxpay-img.png`,
        typeName: '微信零钱'
      // },
      // {
      //   typeIndex: 0,
      //   typeImg: `${_imgUrlHost}alipay-img.png`,
      //   typeName: '支付宝'
      // },
      // {
      //   typeIndex: 1,
      //   typeImg: `${_imgUrlHost}card-img.png`,
      //   typeName: '银行卡'
      }
    ],
    bankType: [
      '中国工商银行', '中国农业银行', '中国银行', '中国建设银行', '中国交通银行',
      '招商银行', '浦发银行', '民生银行', '兴业银行', '深圳发展银行', '华夏银行', '光大银行',
      '广发银行', '中信银行', '北京银行', '上海银行', '南京银行', '邮政储蓄银行'
    ],
    bank_type: '',
    accountHints: [
      {
        name: '支付宝帐户',
        account_type: '帐户类型',
        account_name: '真实姓名',
        account_no: '支付宝帐号'
      },
      {
        name: '银行帐户',
        account_type: '开户银行',
        account_name: '开户名',
        account_no: '银行卡号'
      },
      {
        name: '收款人',
        account_type: '帐户类型',
        account_name: '真实姓名',
        account_no: '微信帐号'
      }
    ],
    selectedAccountIndex: 2,
    account: {
      // 开户银行
      accountType: '',
      // 帐户名称
      accountName: '',
      // 银行帐号
      accountNo: ''
    },
    // 提现金额
    amount: null,
    alipayWithdrawAccount: null,
    wechatAccount: null,
    bankCard: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    _this = this;
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    _this.getAccountInfo();
  },
  /**
   * 切换提现帐户类型
   */
  handleCheck(e) {
    let selectedAccountIndex = parseInt(e.currentTarget.dataset.index);
    if (selectedAccountIndex === 0) {
      let _account = _this.data.alipayWithdrawAccount || {};
      this.setData({
        'account.accountName': _account.accountName || '',
        'account.accountNo': _account.accountNo || '',
      });
    } else if (selectedAccountIndex === 1) {
      let _bank = _this.data.bankCard || {};
      this.setData({
        'account.accountName': _bank.openAccountName || '',
        'account.accountNo': _bank.cardNo || '',
        'bank_type': _bank.bankName || '',
      });
    } else {
      let _account = _this.data.wechatAccount || {};
      this.setData({
        'account.accountName': _account.accountName || ''
      });
    };
    this.setData({ selectedAccountIndex});
  },
  /**
   * 获取默认的帐户信息
   */
  getAccountInfo () {
    API_Account.queryWithdrawAcount().then((res) => {
      const { alipayWithdrawAccount, wechatAccount, bankCard } = res;
      this.setData({
        selectedAccountIndex: 2,
        alipayWithdrawAccount,
        wechatAccount,
        bankCard
      });
      if (wechatAccount) {
        this.setData({
          account: {
            accountName: wechatAccount.accountName
          }
        });
      };
    });
  },
  /**
   * 切换银行卡
   */
  bindBankChange(e) {
    this.setData({ 'bank_type': this.data.bankType[e.detail.value] })
  },
  /**
   * 提现金额
   */
  changeAmount(e) {
    this.setData({ 'amount': e.detail.value })
  },
  /**
   * 输入帐名
   */
  changeAccountName(e) {
    this.setData({ 'account.accountName': e.detail.value })
  },
  /**
   * 输入帐号
   */
  changeAccountNo(e) {
    this.setData({ 'account.accountNo': e.detail.value })
  },
  /**
   * 提交
   */
  submitForm() {
    const params = JSON.parse(JSON.stringify(this.data.account));
    const { amount, selectedAccountIndex } = this.data;
    if (!amount || Number(amount) <= 0) {
      wx.showToast({ title: '请输入有效的提现金额！', icon: 'none' });
      return;
    };
    if(amount < 1) {
      wx.showToast({ title: '提现金额1元起提！', icon: "none" });
      return;
    };
    if (selectedAccountIndex === 0) {
      const { alipayWithdrawAccount } = this.data;
      let _toastTitle = !params.accountName ? '请输入真实姓名！' : !params.accountNo ? '请输入支付宝帐号！' : null;
      if (_toastTitle) {
        wx.showToast({ title: _toastTitle, icon: 'none' });
        return;
      };
      if (!alipayWithdrawAccount) {
        // 无帐户则绑帐户
        _this.addAccount(1);
      } else {
        // 有帐户直接提现
        _this.applyWithdraw();
      };
    } else if (selectedAccountIndex === 1) {
      const { bank_type, bankCard } = this.data;
      let _toastTitle = !bank_type ? '请选择开户银行！' : !params.accountName ? '请输入帐户名称！' : !params.accountNo ? '请输入银行卡帐号！' : null;
      if (_toastTitle) {
        wx.showToast({ title: _toastTitle, icon: 'none' });
        return;
      };
      if (!bankCard) {
        // 无银行卡先绑卡
        _this.addBankCard();
      } else {
        // 有银行卡直接提现
        _this.applyWithdraw();
      };
    } else {
      const { wechatAccount } = this.data;
      if (!params.accountName) {
        wx.showToast({ title: '请输入真实姓名！', icon: 'none' });
        return;
      };
      if (!wechatAccount) {
        // 无帐户则绑帐户
        _this.addAccount(2);
      } else {
        // 有帐户直接提现
        _this.applyWithdraw();
      };
    };
    // app.sendNotice('WITHDRAWAL_NOTICE,WITHRESULT_NOTICE')
  },
  /**
   * 绑卡
   */
  addBankCard() {
    let params = {
      bank_name: _this.data.bank_type,
      card_no: _this.data.account.accountNo,
      open_account_name: _this.data.account.accountName,
    };
    API_Account.bindBankCard(params).then((resp) => {
      if (resp.success) {
        _this.applyWithdraw();
      };
    });
  },
  /**
   * 绑帐户(_type:支付宝=1/微信=2)
   */
  addAccount(_type) {
    const { accountName, accountNo } = this.data.account;
    let params = {
      account_name: accountName,
      account_no: _type === 1 ? accountNo : wx.getStorageSync('user').mobile,
      type: _type
    };
    API_Account.bindAccount(params).then((resp) => {
      if(resp.success) {
        _this.applyWithdraw();
      }
    });
  },
  /**
   * 申请提现
   */
  applyWithdraw() {
    let { selectedAccountIndex, amount, account, bank_type } = this.data;
    let params = {
      account_id: wx.getStorageSync('accountId'),
      amount: amount
    };
    // withdraw_type:打款类型(1:线上;2:线下);withdraw_channel:提现渠道(1:银行卡;2:支付宝;3:微信);
    if (selectedAccountIndex === 0) {
      Object.assign(params, {
        withdraw_channel: 2,
        withdraw_type: 2,
        other_account_type_name: '支付宝',
        other_account_name: account.accountName,
        other_account_no: account.accountNo
      });
    } else if (selectedAccountIndex === 1) {
      Object.assign(params, {
        withdraw_channel: 1,
        withdraw_type: 2,
        bank_name: bank_type,
        card_no: account.accountNo,
        open_account_name: account.accountName
      });
    } else {
      Object.assign(params, {
        withdraw_channel: 3,
        withdraw_type: 1,
        other_account_type_name: '微信零钱',
        other_account_name: account.accountName,
        other_account_no: wx.getStorageSync('user').mobile
      });
    };
    API_Account.applyWithdraw(params).then((resp) => {
      if (resp.success) {
        wx.showModal({
          title: '提现申请已提交',
          content: '将在1-3个工作日内审核，请耐心等待',
          confirmColor: '#f42424',
          confirmText: '我知道了',
          showCancel: false,
          success(res) {
            // WITHDRAWAL_NOTICE_1:提现审核通过;WITHDRAWAL_NOTICE_2:提现审核驳回;WITHRESULT_NOTICE_1:提现结果到账; WITHRESULT_NOTICE_2:提现结果失败
            app.sendNotice('WITHDRAWAL_NOTICE,WITHRESULT_NOTICE');
            if (res.confirm) {
              wx.navigateBack({});
            };
          }
        });
      } else {
        wx.showToast({ title: resp.message, icon: 'none' });
      };
    }).catch(error => {
      wx.showToast({ title: '提现申请提交失败', icon: 'none' });
    });
  }
})
